'use strict';

const Service = require('egg').Service;

class AppointmentService extends Service {
  // 创建预约
  async create(data) {
    const {
      property_id,
      user_id,
      appointment_date,
      contact_phone,
      contact_name,
      remark
    } = data;

    // 参数验证
    if (!property_id || !user_id || !appointment_date || !contact_phone) {
      throw new Error('必填字段不能为空');
    }

    // 检查预约时间是否在未来
    const appointmentTime = new Date(appointment_date);
    if (appointmentTime <= new Date()) {
      throw new Error('预约时间必须是未来时间');
    }

    // 检查是否已有相同时间的预约
    const existingAppointment = await this.app.mysql.get('appointments', {
      property_id,
      appointment_date: appointmentTime,
      status: ['pending', 'confirmed']
    });

    if (existingAppointment) {
      throw new Error('该时间段已有预约，请选择其他时间');
    }

    const result = await this.app.mysql.insert('appointments', {
      property_id,
      user_id,
      appointment_date: appointmentTime,
      contact_phone,
      contact_name,
      remark,
      status: 'pending',
      created_at: new Date(),
      updated_at: new Date()
    });

    return result;
  }

  // 获取用户的预约列表
  async getUserAppointments(userId, query = {}) {
    const { page = 1, pageSize = 10, status } = query;
    const offset = (Number(page) - 1) * Number(pageSize);
    const limit = Number(pageSize);

    let whereClause = 'a.user_id = ?';
    const params = [userId];

    if (status) {
      whereClause += ' AND a.status = ?';
      params.push(status);
    }

    const sql = `
      SELECT 
        a.*,
        h.title as property_title,
        h.address as property_address,
        h.price as property_price,
        h.images as property_images,
        u.username as owner_name,
        u.phone as owner_phone
      FROM appointments a
      LEFT JOIN houses h ON a.property_id = h.id
      LEFT JOIN users u ON h.user_id = u.id
      WHERE ${whereClause}
      ORDER BY a.appointment_date DESC
      LIMIT ? OFFSET ?
    `;

    const countSql = `
      SELECT COUNT(*) AS total
      FROM appointments a
      WHERE ${whereClause}
    `;

    const [rows, countRows] = await Promise.all([
      this.app.mysql.query(sql, [...params, limit, offset]),
      this.app.mysql.query(countSql, params)
    ]);

    const total = countRows?.[0]?.total || 0;

    const items = rows.map(r => {
      let images = [];
      try {
        if (r.property_images) {
          const arr = JSON.parse(r.property_images);
          if (Array.isArray(arr)) images = arr;
        }
      } catch (_) {}

      return {
        id: r.id,
        property_id: r.property_id,
        property_title: r.property_title,
        property_address: r.property_address,
        property_price: Number(r.property_price),
        property_images: images,
        owner_name: r.owner_name,
        owner_phone: r.owner_phone,
        appointment_date: r.appointment_date,
        contact_phone: r.contact_phone,
        contact_name: r.contact_name,
        remark: r.remark,
        status: r.status,
        created_at: r.created_at,
        updated_at: r.updated_at
      };
    });

    return { total, items };
  }

  // 获取房源的预约列表（房东查看）
  async getPropertyAppointments(propertyId, query = {}) {
    const { page = 1, pageSize = 10, status } = query;
    const offset = (Number(page) - 1) * Number(pageSize);
    const limit = Number(pageSize);

    let whereClause = 'a.property_id = ?';
    const params = [propertyId];

    if (status) {
      whereClause += ' AND a.status = ?';
      params.push(status);
    }

    const sql = `
      SELECT 
        a.*,
        u.username as user_name,
        u.phone as user_phone
      FROM appointments a
      LEFT JOIN users u ON a.user_id = u.id
      WHERE ${whereClause}
      ORDER BY a.appointment_date DESC
      LIMIT ? OFFSET ?
    `;

    const countSql = `
      SELECT COUNT(*) AS total
      FROM appointments a
      WHERE ${whereClause}
    `;

    const [rows, countRows] = await Promise.all([
      this.app.mysql.query(sql, [...params, limit, offset]),
      this.app.mysql.query(countSql, params)
    ]);

    const total = countRows?.[0]?.total || 0;

    const items = rows.map(r => ({
      id: r.id,
      user_id: r.user_id,
      user_name: r.user_name,
      user_phone: r.user_phone,
      appointment_date: r.appointment_date,
      contact_phone: r.contact_phone,
      contact_name: r.contact_name,
      remark: r.remark,
      status: r.status,
      created_at: r.created_at,
      updated_at: r.updated_at
    }));

    return { total, items };
  }

  // 更新预约状态
  async updateStatus(id, status, userId = null) {
    const whereCondition = { id };
    
    // 如果提供了userId，检查权限
    if (userId) {
      const appointment = await this.app.mysql.get('appointments', { id });
      if (!appointment) {
        throw new Error('预约不存在');
      }
      
      // 检查是否是预约者本人或房源所有者
      const property = await this.app.mysql.get('houses', { id: appointment.property_id });
      if (appointment.user_id !== userId && property.user_id !== userId) {
        throw new Error('无权限操作');
      }
    }

    const result = await this.app.mysql.update('appointments', {
      status,
      updated_at: new Date()
    }, {
      where: whereCondition
    });

    return result;
  }

  // 取消预约
  async cancel(id, userId) {
    const appointment = await this.app.mysql.get('appointments', { id });
    if (!appointment) {
      throw new Error('预约不存在');
    }

    if (appointment.user_id !== userId) {
      throw new Error('无权限操作');
    }

    if (appointment.status === 'cancelled') {
      throw new Error('预约已取消');
    }

    if (appointment.status === 'completed') {
      throw new Error('预约已完成，无法取消');
    }

    return await this.updateStatus(id, 'cancelled', userId);
  }

  // 获取预约详情
  async getDetail(id) {
    const sql = `
      SELECT 
        a.*,
        h.title as property_title,
        h.address as property_address,
        h.price as property_price,
        h.images as property_images,
        u.username as user_name,
        u.phone as user_phone,
        owner.username as owner_name,
        owner.phone as owner_phone
      FROM appointments a
      LEFT JOIN houses h ON a.property_id = h.id
      LEFT JOIN users u ON a.user_id = u.id
      LEFT JOIN users owner ON h.user_id = owner.id
      WHERE a.id = ?
    `;

    const rows = await this.app.mysql.query(sql, [id]);
    if (!rows || !rows.length) return null;

    const r = rows[0];
    let images = [];
    try {
      if (r.property_images) {
        const arr = JSON.parse(r.property_images);
        if (Array.isArray(arr)) images = arr;
      }
    } catch (_) {}

    return {
      id: r.id,
      property_id: r.property_id,
      property_title: r.property_title,
      property_address: r.property_address,
      property_price: Number(r.property_price),
      property_images: images,
      user_id: r.user_id,
      user_name: r.user_name,
      user_phone: r.user_phone,
      owner_name: r.owner_name,
      owner_phone: r.owner_phone,
      appointment_date: r.appointment_date,
      contact_phone: r.contact_phone,
      contact_name: r.contact_name,
      remark: r.remark,
      status: r.status,
      created_at: r.created_at,
      updated_at: r.updated_at
    };
  }
}

module.exports = AppointmentService;
